<script lang="ts" module>
    export const RowContextKey = Symbol("RowContextKey");
</script>

<script lang="ts">
    import { setContext } from "svelte";
    import { createGutter } from "../utils/createGridOffset";
    import { useClassList } from "../utils/useClassList";
    import { useStyle } from "../utils/useStyle";
    import type { RowProps } from "./Row";

    const props: RowProps = $props();
    const { justify, align, gutter, ...others } = props;
    const gutterClass = typeof props.gutter === "object" ? createGutter(props.gutter) : {};
    const classList = $derived(
        useClassList(props, "cm-row", {
            ...gutterClass,
            [`cm-row-${props.justify}`]: props.justify,
            [`cm-row-${props.align}`]: props.align,
        }),
    );
    const newStyle = $derived.by(() => {
        const obj: any = {};
        let half = 0;
        let rowGutter = 0;
        if (typeof props.gutter === "number") {
            half = props.gutter ? props.gutter / 2 : 0;
            rowGutter = props.gutter || 0;
        }
        if (Array.isArray(props.gutter)) {
            half = props.gutter[0] ? props.gutter[0] / 2 : 0;
            rowGutter = props.gutter[1] || 0;
        }

        if (half) {
            obj["margin-left"] = `-${half}px`;
            obj["margin-right"] = `-${half}px`;
        }
        if (rowGutter) {
            obj["row-gap"] = `${rowGutter}px`;
        }
        return useStyle(props, obj);
    });

    setContext(RowContextKey, {
        gutter: props.gutter || 0,
    });
</script>

<div {...others} class={classList} style={newStyle}>{@render props.children?.()}</div>
